package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-11-16
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    private IAuditService auditService;

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        User user = UserThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId,user.getUserId());
        //状态
        if(dto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        //标题
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //频道
        if(dto.getChannelId() != null){
            queryWrapper.like(WmNews::getChannelId,dto.getChannelId());
        }

        //发布时间
        if(dto.getBeginPubDate() != null && dto.getBeginPubDate() != null){
            queryWrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
            queryWrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        }
        //发布时间排序
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        Page<WmNews> page1 = this.page(page,queryWrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }

    @Override
    public ResponseResult<WmNews> submit(WmNewsDto dto) {

        User user = UserThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if(dto.getId() != null){
            deleteRelation(dto.getId());
        }
        //构建一个wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        List<ImageDto> imageDtoList = dto.getImages();
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        List<ImageDto> contenImageList = getImagesFromContent(wmNews.getContent());
        if(dto.getType() == -1){
            //获取内容图片

            int size = contenImageList.size();
            if(size ==0){
                wmNews.setType(0);
            }else if(size > 0 && size < 3){
                wmNews.setType(1);
                imageDtoList = contenImageList.subList(0,1);
            }else{
                wmNews.setType(3);
                imageDtoList = contenImageList.subList(0,3);
            }
        }
        wmNews.setImages(JSON.toJSONString(imageDtoList));
        this.saveOrUpdate(wmNews);
        //判断是否为草稿
        if(dto.getStatus() == 1){
            //获取内容
            saveRelation(contenImageList,wmNews.getId(),0);
            saveRelation(imageDtoList,wmNews.getId(),1);
            //实现审核的操作
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    private void saveRelation(List<ImageDto> contenImageList, Integer newsId, int type) {
        int ord = 0;
        for (ImageDto imageDto : contenImageList) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();

            //wmNewsMaterial.setId();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(ord);
            ord++;
            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }

    private List<ImageDto> getImagesFromContent(String content) {

        List<ImageDto> imagedtoList = new ArrayList<>();
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtoList) {
            if(contentDto.getType().equals("image")){
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imagedtoList.add(imageDto);
            }
        }
        return imagedtoList;
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    private void deleteRelation(Integer newsId) {
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,newsId);
        wmNewsMaterialService.remove(queryWrapper);
    }
}
